package com.hdd.utils.wx;


import com.hdd.biz.task.WechatFlushAccessTokenJob;
import com.hdd.enums.CommonEnum;
import com.hdd.model.template.TemplateData;
import com.hdd.model.template.TemplateMessage;
import com.hdd.model.template.TemplateValue;
import com.hdd.utils.DateUtil;
import com.hdd.utils.JsonUtil;
import com.hdd.utils.http.HttpClient;
import com.hdd.utils.http.OkHttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * @Description:
 * @author ;xuhu
 * @Date: 2020-11-16 14:42
**/

@Component
public class WxSendTemplateUtil {

    private static final Logger logger = LoggerFactory.getLogger(WxSendTemplateUtil.class);

    @Autowired
    private WechatFlushAccessTokenJob wechatFlushAccessTokenJob;

    private String templateUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send";

    public boolean illegalAccount(String openId, String context, String result){
        if (openId == null || "".equals(openId)) {
            logger.info("openID是空");
            return false;
        }

        TemplateMessage templateMessage = buildIllegalTemplate(openId, context, result);

        String accessToken = wechatFlushAccessTokenJob.getAccessToken();
        logger.info("accessToken：{}", accessToken);
        OkHttpResponse<String> json = HttpClient.postJson(templateUrl + "?access_token=" + accessToken, JsonUtil.toJsonString(templateMessage));

        if (json.isSuccess()) {
            Map<String, Object> map = JsonUtil.toMap(json.getData());
            logger.info("发送模板消息结果：{}", JsonUtil.toJsonString(map));
            String errCode = map.get("errcode").toString();
            if ("0".equals(errCode)) {
                return true;
            } else if ("40001".equals(errCode) || "40014".equals(errCode)) {
                //可能是AccessToken 过期或无效，刷新重试
                accessToken = wechatFlushAccessTokenJob.getNewAccessToken();
                logger.info("accessToken2：{}", accessToken);
                json = HttpClient.postJson(templateUrl + "?access_token=" + accessToken, JsonUtil.toJsonString(templateMessage));
                map = JsonUtil.toMap(json.getData());
                logger.info("第二次发送模板消息结果：{}", JsonUtil.toJsonString(map));
                return "0".equals(map.get("errcode").toString());
            }
        }

        return false;
    }

    private TemplateMessage buildIllegalTemplate(String openId, String context, String result) {
        TemplateMessage templateMessage = new TemplateMessage();
        templateMessage.setTouser(openId);
        templateMessage.setTemplate_id(CommonEnum.templateId.account.getValue());

        TemplateData templateData = new TemplateData();

        TemplateValue first = new TemplateValue();
        first.setValue("您的账号存在违规行为");
        first.setColor("#173177");
        templateData.setFirst(first);

        TemplateValue keyword1 = new TemplateValue();
        keyword1.setValue(context);
        keyword1.setColor("#173177");
        templateData.setKeyword1(keyword1);

        TemplateValue keyword2 = new TemplateValue();
        keyword2.setValue(result);
        keyword2.setColor("#173177");
        templateData.setKeyword2(keyword2);

        TemplateValue keyword3 = new TemplateValue();
        keyword3.setValue(DateUtil.format(new Date(),"yyyy年MM月dd日 HH:mm"));
        keyword3.setColor("#173177");
        templateData.setKeyword3(keyword3);

        TemplateValue remark = new TemplateValue();
        remark.setValue("特此提醒您不合理的行为可能会导致您的账户受到限制。");
        remark.setColor("#173177");
        templateData.setRemark(remark);

        templateMessage.setData(templateData);

        return templateMessage;
    }
}